﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Common;
using DevelopTool.Model.NoteModels;
using LiteDB;

namespace DevelopTool.Bll.NoteBlls
{
    public class NoteFileBll
    {

        public NoteFileBll()
        {
            using(var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<NoteFile>();
                col.EnsureIndex(x => x.NoteId);
                col.EnsureIndex(x => x.FileId);
                col.EnsureIndex(x => x.Filename);
                col.EnsureIndex(x => x.CreateTime);
                col.EnsureIndex(x => x.Id);
            }
        }

        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="noteId"></param>
        /// <returns></returns>
        public List<NoteFile> GetList(int noteId)
        {
            using(var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<NoteFile>();

                var noteFiles = col.Find(it => it.NoteId == noteId).ToList();
                return noteFiles;
            }
        }


        /// <summary>
        /// 批量上传文件
        /// </summary>
        /// <param name="noteId"></param>
        /// <param name="noteFiles"></param>
        /// <returns></returns>
        public List<NoteFile> UploadFiles(int noteId,List<NoteFile> noteFiles)
        {
            using(var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                for(int i = 0 ; i < noteFiles.Count ; i++)
                {
                    //压缩文件
                    string compressFilePath = ZipHelper.FilesCompress(noteFiles[i].FilePath,"");

                    string fileId = $"$/note/{noteId}/{Guid.NewGuid().ToString("N")}";
                    LiteFileInfo liteFileInfo = db.FileStorage.Upload(fileId,compressFilePath);//保存文件到数据库

                    FileInfo fileInfo = new FileInfo(noteFiles[i].FilePath);

                    noteFiles[i].Filename = fileInfo.Name;
                    noteFiles[i].MimeType = liteFileInfo.MimeType;
                    noteFiles[i].OriginalLength = fileInfo.Length;
                    noteFiles[i].CreateTime = liteFileInfo.UploadDate;
                    noteFiles[i].CompressLength = liteFileInfo.Length;
                    noteFiles[i].NoteId = noteId;
                    noteFiles[i].FileId = liteFileInfo.Id;

                    File.Delete(compressFilePath);//删除临时压缩文件
                }

                //保存到数据库
                var col = db.GetCollection<NoteFile>();
                col.Insert(noteFiles);
            }
            return noteFiles;
        }




        /// <summary>
        /// 保存文件到磁盘
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="savePath"></param>
        public void SaveAs(int noteFileId,string savePath)
        {
            using(var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<NoteFile>();

                var noteFile = col.FindById(noteFileId);
                LiteFileInfo fileInfo = db.FileStorage.FindById(noteFile.FileId);//从数据库中取出文件

                //如果是压缩的文件，先保存到临时目录，解压缩后再存到指定目录
                string filePath = Path.Combine(GlobalData.AppTempDirectory,fileInfo.Filename);
                fileInfo.SaveAs(filePath);

                //解压缩文件，保存到指定路径
                ZipHelper.FilesDecompress(filePath,savePath);

                File.Delete(filePath);//删除临时压缩文件

            }
        }



        /// <summary>
        /// 删除文件（物理删除）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            using(var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<NoteFile>();
                var noteFile = col.FindById(id);

                db.FileStorage.Delete(noteFile.FileId);
                var result = col.Delete(noteFile.Id);

                return result;
            }
        }


        /// <summary>
        /// 删除所有笔记附件（文件）
        /// </summary>
        /// <returns></returns>
        public bool DeleteAllFiles(string filename,string password)
        {

            ConnectionString connectionString = new ConnectionString
            {
                Filename = filename,
                Password = password
            };

            using(var db = new LiteDatabase(connectionString))
            {
                var files = db.FileStorage.FindAll();
                foreach(var file in files)
                {
                    db.FileStorage.Delete(file.Id);
                }
                return true;
            }
        }

    }
}
